// pages/downloadVideo/downloadVideo.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    downloadData: {
      progress: 0,
      totalBytesWritten: 0,
      totalBytesExpectedToWrite: 0
    },
    videoUrlDone: '',
    videoUrl:
      'http://wxsnsdy.tc.qq.com/105/20210/snsdyvideodownload?filekey=30280201010421301f0201690402534804102ca905ce620b1241b726bc41dcff44e00204012882540400&bizid=1023&hy=SH&fileparam=302c020101042530230204136ffd93020457e3c4ff02024ef202031e8d7f02030f42400204045a320a0201000400'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {},

  handleDownloadVideo() {
    // TODO
    if (this.data.downloadData.totalBytesExpectedToWrite) {
      wx.showToast({
        title: '您已经下载过啦',
        icon: 'none'
      })
      return
    }

    const downloadTask = wx.downloadFile({
      url: this.data.videoUrl,
      success: ({ tempFilePath }) => {
        this.setData({
          videoUrlDone: tempFilePath
        })

        wx.showToast({
          title: '下载完成！',
          icon: 'none'
        })
      }
    })

    downloadTask.onProgressUpdate((res) => {
      this.setData({
        downloadData: {
          progress: res.progress,
          totalBytesWritten: (res.totalBytesWritten / 1024 / 1024).toFixed(2),
          totalBytesExpectedToWrite: (res.totalBytesExpectedToWrite / 1024 / 1024).toFixed(2)
        }
      })
    })
  }
})
